package com.wz.token.interceptor;

import com.alibaba.fastjson.JSON;
import com.wz.token.TokenContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {

    TokenContext tokenContext;

    public TokenInterceptor(TokenContext token) {
        this.tokenContext = token;
    }

    public TokenInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String xtoken = request.getHeader("xtoken");
        if (null == xtoken) {
            getWrite(response).write(fail("无权访问"));
            return false;
        }
        //验证token有效
        int rs = tokenContext.validateToken(xtoken);
        if (rs == 2) {
            //token无效
            getWrite(response).write(fail("token无效"));
            return false;
        } else if (rs == 3) {
            getWrite(response).write(fail("token已过期"));
            //token过期
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    /**
     * 将map转换为json格式字符串
     *
     * @param msg
     * @return
     */
    String fail(String msg) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", msg);
        return JSON.toJSONString(map);
    }


    PrintWriter getWrite(HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        try {
            return response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}